App.controller('mediaBusController', ['$rootScope', '$scope', '$state', 'Page', function ($rootScope, $scope, $state, Page) {
	
	Page.ajaxPostQuiet('media/bus/companys.do', null, function (resp) {
    	  $scope.companys = resp.data;
    });
	
	Page.ajaxGetQuiet('media/bus/mediatypes.do', null, function (resp) {
        $scope.mediaTypes = resp.data;
    });
	
	Page.ajaxPostQuiet('busType/query.do', null, function (resp) {
        $scope.busTypes = resp.data;
    });
	
	$scope.mediaBusGrid = {
		options : {
			lazy : false,
			bAutoWidth:false
		},
		column_defs: [
				{
	            	target: 1,
	            	template: function(row){
						var content = '<a href="javascript:void(0)" ed-click="viewBusMediaInfo">'+row.plateNo+'</a>'
		                    + '<a href="javascript:void(0);" ed-click="viewBusPosition" title="定位" class="icon-pointer" style="padding-left: 10px;font-size:13px;"></a>'; 
		              return content;
	            	}
	            },
	            {
	            	target: 7,
	            	template: function(row){
	            	    var busType = row.busType;
	            	    var typeImg = '';
	            		$($scope.busTypes).each(function(index, type) {
		        	 		if(type.typeCode == row.busType){
		        	 			busType = type.typeName;
		        	 			typeImg = type.descImg;
		        	 			return;
		        	 		}
		         		});
	            		if(typeImg != ''){
	            			return '<a class="mix-preview"  href="'+($scope.nginxPath + typeImg)+'" data-rel="fancybox-button">'+ busType +'</a>';
	            		}else{
	            			return busType;
	            		}
	            	}
	            },
	            {
	            	target: 12,
	            	buttons: [
	                    {
	                        name: '编辑',
	                        clazz: 'btn-edit',
	                        icon: 'fa-edit',
	                        event: function(row){
	                    		$scope.mediaBus = row;
	                    		$scope.busEditModal.show();
	                        }
	                    },
	                    {
	                        name: '媒体资源',
	                        clazz: 'btn-success',
	                        icon: 'fa-file-text-o',
	                        event: function(row){
	                    		$scope.mediaBus = row;
					    		$scope.busResourcesModal.show();
	                        }
	                    },
	                    {
	                        name: '异动查询',
	                        clazz: 'purple',
	                        icon: 'fa-search',
	                        event: function(row){
								Page.ajaxPost('media/resource/bus/transQuery.do', {busId : row.busId}, function (resp) {

									var returnData = resp.data;
									$scope.sortTransList(returnData);
									//Page.notice('车辆数据刷新完成!');
									$scope.busTransModal.show();
								});
	                        }
	                    }
                    ]
	            }
		],
		viewBusMediaInfo : function(row){
	      $scope.busMediaInfoModal.setBusId(row.busId).show();
	    },
		viewBusPosition : function(row){
			$scope.busLineModal.init(row).show();
		},
		syncMediaBus : function(){
			Page.ajaxPost('media/bus/refresh.do', null, function (resp) {
				 Page.notice('车辆数据刷新完成!');
		         $scope.mediaBusGrid.query();
		    });
		}
	};

	$scope.sortTransList = function(returnData) {
		var companyInnerTransList = returnData["companyInnerTransList"];
		var companyTransList = returnData["companyTransList"];
		var vehicleUsingList = returnData["vehicleUsingList"];

		var total = angular.extend([],companyInnerTransList,companyTransList,vehicleUsingList);
		console.log(total);

		total.sort(function(a, b){
			return a < b ? 1 : -1;
		});

		$scope.busTransList = angular.copy(total);
	};

	$scope.busTransModal = {

	};
	
	$scope.busLineModal = {
		init : function(bus){
			this.bus = bus;
			return this;
		},
		onShow : function(){
			this.setTitle("车辆定位【" + this.bus.vehicleNo + "】");
			var self = this;
	       	//高德
	       	var mapDiv = "busLineModalMapDiv";
			var width = $('#' + mapDiv).width();
			var height = $('#' + mapDiv).height();
			this.map = new AMap.Map(mapDiv, {resizeEnable: true,zoom:13,center: [114.296308, 30.595444]});

			Page.notice("正在定位...");
			Page.ajaxPostQuiet('media/bus/gps.do', {vehicleNo : this.bus.vehicleNo,lineNo : this.bus.lineNo}, function (resp) {
				if(resp.data && resp.data.gpsdatatime) {

					$scope.drawLine(resp.data.stationList,self.map);

					var po = AppUtil.GPS.gcj_encrypt(resp.data.latitude*1, resp.data.longitude*1);
					var infoWindow = new AMap.InfoWindow({
						content:self.bus.vehicleNo + '【运行线路：' + resp.data.lineName + '】【最后定位时间：' + resp.data.gpsdatatime +'】【方向角：' + resp.data.direction + '】',
						offset : new AMap.Pixel(-15, -20)
					});
					var busMarker = new AMap.Marker({
						position: [po.lon, po.lat],
						//icon: "./assets/admin/img/map_bus_orange.png",
						icon : new AMap.Icon({imageSize:new AMap.Size(30,30),image:'./assets/admin/img/map_bus_orange.png'}),
						offset: new AMap.Pixel(-20, -35),
						map:self.map
					}).on('click',function(e){
							infoWindow.open(self.map, e.target.getPosition());
					});
					infoWindow.open(self.map, busMarker.getPosition());
				}
		    });



			//if(this.bus.lineNo){
			//	AMap.service(["AMap.LineSearch"], function() {
			//	    var linesearch = new AMap.LineSearch({
			//	    	city:'027',
			//	    	extensions:'all'
			//	    });
			//	    linesearch.search(self.bus.lineNo, function(status, result) {
			//            if (status === 'complete' && result.info === 'OK' && result.lineInfo.length > 0) {
			//              	var busArr = result.lineInfo[0].path;
	         //       		var stops = result.lineInfo[0].via_stops;
	         //       		var startPot = stops[0].location;
	         //       		var endPot = stops[stops.length - 1].location;
	         //
	         //       		new AMap.Marker({
			//		            map: self.map,
			//		            position: [startPot.lng, startPot.lat], //基点位置
			//		            icon: "http://webapi.amap.com/theme/v1.3/markers/n/start.png",
			//		            zIndex: 10
			//		        });
			//		        new AMap.Marker({
			//		            map: self.map,
			//		            position: [endPot.lng, endPot.lat], //基点位置
			//		            icon: "http://webapi.amap.com/theme/v1.3/markers/n/end.png",
			//		            zIndex: 10
			//		        });
			//		        //绘制乘车的路线
			//		        busPolyline = new AMap.Polyline({
			//		            map: self.map,
			//		            path: busArr,
			//		            strokeColor: "#09f",//线颜色
			//		            strokeOpacity: 0.8,//线透明度
			//		            strokeWeight: 5//线宽
			//		        });
			//            }
			//    	});
			//	});
			//}
			
			setTimeout(function() {
				self.map.setFitView();
			},300);
			
   		}
	};

	$scope.drawLine = function(stationList,map) {

		if(stationList != undefined && stationList.length > 0) {
			var startStop = stationList[0];
			//console.log("没有转之前:" + parseFloat(startStop.longitude) / 60 + "------" + parseFloat(startStop.latitude) / 60);
			var zbObj1 = AppUtil.GPS.gcj_encrypt(parseFloat(startStop.latitude) / 60, parseFloat(startStop.longitude) / 60);
			//console.log("没有转之后:" + zbObj1.lon + "------" + zbObj1.lat);
			var stopMarker = new AMap.Marker({
				map: map,
				position: [zbObj1.lon, zbObj1.lat], //基点位置
				icon: "http://webapi.amap.com/theme/v1.3/markers/n/start.png",
				zIndex: 10
			});

			stopMarker.info = new AMap.InfoWindow({
				content: startStop.stationName,
				offset: new AMap.Pixel(0, -30)
			});
			stopMarker.on('click', function(e) {
				e.target.info.open(map, e.target.getPosition())
			});


			var endStop = stationList[stationList.length - 1];
			var zbObj2 = AppUtil.GPS.gcj_encrypt(parseFloat(endStop.latitude) / 60, parseFloat(endStop.longitude) / 60);
			var endMarker = new AMap.Marker({
				map: map,
				position: [zbObj2.lon, zbObj2.lat], //基点位置
				icon: "http://webapi.amap.com/theme/v1.3/markers/n/end.png",
				zIndex: 10
			});

			endMarker.info = new AMap.InfoWindow({
				content: endStop.stationName,
				offset: new AMap.Pixel(0, -30)
			});
			endMarker.on('click', function(e) {
				e.target.info.open(map, e.target.getPosition())
			});

			var lineArr = [];
			for (var i = 0; i < stationList.length; i++) {
				var station = stationList[i];
				var zbObj3 = AppUtil.GPS.gcj_encrypt(parseFloat(station.latitude) / 60, parseFloat(station.longitude) / 60);
				if(i != 0 && i != stationList.length - 1) {
					var marker = new AMap.Marker({
						map: map,
						position: [zbObj3.lon, zbObj3.lat], //基点位置
						icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png",
						zIndex: 10
					});
					marker.info = new AMap.InfoWindow({
						content: station.stationName,
						offset: new AMap.Pixel(0, -30)
					});
					marker.on('click', function(e) {
						e.target.info.open(map, e.target.getPosition())
					});
				}
				lineArr.push([zbObj3.lon, zbObj3.lat]);

			}



			busPolyline = new AMap.Polyline({
				map: map,
				path: lineArr,
				strokeColor: "#09f",//线颜色
				strokeOpacity: 0.8,//线透明度
				strokeWeight: 5//线宽
			});
		}

		//AMap.service(["AMap.LineSearch"], function() {
		//		var linesearch = new AMap.LineSearch({
		//			city:'027',
		//			extensions:'all'
		//		});
		//		linesearch.search(self.bus.lineNo, function(status, result) {
		//			if (status === 'complete' && result.info === 'OK' && result.lineInfo.length > 0) {
		//				var busArr = result.lineInfo[0].path;
		//			var stops = result.lineInfo[0].via_stops;
		//			var startPot = stops[0].location;
		//			var endPot = stops[stops.length - 1].location;
        //
		//			new AMap.Marker({
		//					map: self.map,
		//					position: [startPot.lng, startPot.lat], //基点位置
		//					icon: "http://webapi.amap.com/theme/v1.3/markers/n/start.png",
		//					zIndex: 10
		//				});
		//				new AMap.Marker({
		//					map: self.map,
		//					position: [endPot.lng, endPot.lat], //基点位置
		//					icon: "http://webapi.amap.com/theme/v1.3/markers/n/end.png",
		//					zIndex: 10
		//				});
		//				//绘制乘车的路线
		//				busPolyline = new AMap.Polyline({
		//					map: self.map,
		//					path: busArr,
		//					strokeColor: "#09f",//线颜色
		//					strokeOpacity: 0.8,//线透明度
		//					strokeWeight: 5//线宽
		//				});
		//			}
		//		});
		//});

	};

	
	$scope.busMediaInfoModal = {
		setBusId : function(busId){
		  this.busId = busId;
		  return this;
		},
		onShow : function(){
		  Page.ajaxGetQuiet('media/bus/' + this.busId + '/info.do', null, function (resp) {
			$scope.mediaBus = resp.data;

			$scope.mediaBus.busImgs = [];
			if($scope.mediaBus.busImg && $scope.mediaBus.busImg != ''){
				var imgs = $scope.mediaBus.busImg.split('|');
				$(imgs).each(function(index, img) {
					$scope.mediaBus.busImgs.push({
						path: img
					});
				});
			}
		  });
		}
	};
	
	$scope.busEditModal = {
		onShow : function(){
		  	$scope.mediaBus = $scope.mediaBus || {};
		   	
			$scope.mediaBus.file = {
				path: $scope.mediaBus.busImg
			};
			
			$scope.mediaBus.busImgs = [];
	       	if($scope.mediaBus.busImg && $scope.mediaBus.busImg != ''){
	       		var imgs = $scope.mediaBus.busImg.split('|');
	       		$(imgs).each(function(index, img) {
	       			$scope.mediaBus.busImgs.push({
	       				path: img
	       			});
	       		});
	       	}
   		},
   		removeBusImg : function(img){
        	for(var i = 0 ;i < $scope.mediaBus.busImgs.length; i++){
        		if($scope.mediaBus.busImgs[i].path == img.path){
        			$scope.mediaBus.busImgs.splice(i,1);
        			return;
        		}
        	}
    	},
   		onOkClick : function() {
	    	$scope.busMediaForm.doValidate();
	       	if($scope.busMediaForm.$valid) {
	       		$scope.mediaBus.busImg = '';
	       		$($scope.mediaBus.busImgs).each(function(index, img) {
	       			$scope.mediaBus.busImg = $scope.mediaBus.busImg + (index == 0 ? '' : '|') + img.path;
       			});
				Page.ajaxPost('media/bus/save.do', $scope.mediaBus, function (resp) {
				    Page.notice("车辆信息保存成功!");
				    $scope.busEditModal.hide();
				    $scope.mediaBusGrid.query();
				});
	        }
    	},
    	onHidden : function() {
        	$scope.busMediaForm.reset();
    	}
	};
	
	$scope.busResourcesModal = {
		onShow : function(){
			this.setTitle('车辆资源列表 - ' + $scope.mediaBus.plateNo);
			
			$($scope.mediaTypes).each(function(index, media) {
				  if(!media.items){
					  Page.ajaxPostQuiet('mediaType/' + media.mediaId + '/items.do', null, function (resp) {
						  media.items = resp.data;
					  });
				  }
			});
			
			this.query();
		},
		query : function(){
			$scope.mediaBus.resources = [];
			Page.ajaxGetQuiet('media/resource/list/bus/' + $scope.mediaBus.busId + '.do' , null, function (resp) {
				$scope.mediaBus.resources = resp.data;
			});
		},
		toAdd : function(media){
			$scope.busResourceEditModal.initConfig(media).show();
		},
		toEdit : function(row, media){
			$scope.busResourceEditModal.initConfig(media).initResource(row).show();
		},
		remove : function(row){
			Page.confirm('确认废除该媒体资源?', function(){
				Page.ajaxPost('media/resource/' + row.resourceId + '/remove.do', null, function (resp) {
					$scope.busResourcesModal.query();
				});
			});
		},
		revert : function(row){
			Page.confirm('确认恢复该媒体资源?', function(){
				Page.ajaxPost('media/resource/'+ row.resourceId +'/revert.do', null, function (resp) {
						$scope.busResourcesModal.query();
				});
			});
		}
	};
	
	$scope.busResourceEditModal = {
		media : {},
		resource : {},
		initConfig : function(media){
			this.media = media;
			this.resource = {};
			return this;
		},
		initResource : function(resource){
			this.resource = angular.copy(resource);
			return this;
		},
		onShow : function(){
			this.setTitle('车辆媒体资源编辑 - ' + this.media.mediaName);
			
			this.resource.busId = $scope.mediaBus.busId;
			this.resource.mediaType = this.media.mediaId;
			this.resource.file = {
				path: this.resource.resourceImg
			};
		},
		onOkClick : function() {
	    	$scope.resourceForm.doValidate();
	       	if($scope.resourceForm.$valid) {
	       		this.resource.resourceImg = this.resource.file.path;
	       		Page.ajaxPost('media/resource/save.do', this.resource, function (resp) {
				   	$scope.busResourceEditModal.hide();
				   	$scope.busResourcesModal.query();
				});
	        }
    	},
    	onHidden : function() {
        	$scope.resourceForm.reset();
    	}
	};
}]);
